package com.hongye.broker.interceptor;

import cn.hutool.crypto.SecureUtil;
import com.hongye.broker.service.BrokerService;
import com.hongye.common.exception.ServiceException;
import jdk.nashorn.internal.ir.annotations.Reference;
import jodd.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;

//@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate redisTemplate;
    private final String REDIS_Token="redis_token";
    //固定签名
    private final String appSercret="1309271995";
   

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取头部信息
        String redisToken = request.getHeader("redis_token");
        String timeStamp = request.getHeader("timestamp");
        String sign = request.getHeader("sign");

        if (StringUtil.isEmpty(redisToken)){
            throw new ServiceException("401","token不存在");
        }
        if (StringUtil.isEmpty(timeStamp)){
            throw new ServiceException("401","时间戳不存在");
        }
        if (StringUtil.isEmpty(sign)){
            throw new ServiceException("401","秘钥不存在");
        }

        //验证签名
        ArrayList<Object> obj = new ArrayList<>();
        obj.add(redisToken);
        obj.add(timeStamp);
        obj.add(appSercret);
        String join = StringUtils.join(obj, "|");
        String s = SecureUtil.md5(join);
        if (!s.equals(sign)){
            throw new ServiceException("401","秘钥不存在");
        }
        //判断时间
        long l = System.currentTimeMillis();
        long l1 = Long.parseLong(timeStamp);
        if (l-l1>1000000){
            throw new ServiceException("401","时间超时");
        }

        String s1 = redisTemplate.opsForValue().get(REDIS_Token + redisToken);
        if (StringUtil.isEmpty(s1)){
            throw new ServiceException("401","账户过期,请重新登录");
        }
        return true;
    }
}
